<?php
declare (strict_types = 1);
namespace app\mall\model;
use app\common\self\SelfRedis;
use app\live\model\LiveBroadcast;
use app\live\model\LiveBroadcastGoods;
use app\myself\Bc;
use app\myself\WeixinPay;
use app\order\model\Order;
use app\order\model\OrderGoods;
use app\order\model\OrderInfo;
use app\order\model\PayLog;
use app\user\model\District;
use app\user\model\UserAddress;
use app\user\model\UserGoodsCollect;
use app\user\model\UserLevel;
use app\user\model\UserShareOrder;
use app\user\model\UserWallet;
use app\user\model\WalletOperationLog;
use app\user\model\User;
use app\video\model\Video;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\Model;

use app\common\model\BaseModel;
use app\common\model\Config;
use app\common\self\MyJob;
use app\mall\model\GoodsAttr;
use app\mall\model\GoodsBrand;
use app\mall\service\PayOrder;
use app\shop\model\ShopCoupon;
use think\Request;

Class Goods extends BaseModel
{

    public $field = 'id,name,share,title,default_price,default_discount_price,min_money,max_money,sort,is_activity,sales_volume';

    //字段预处理 格式化
    public function getDefaultPriceAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    public function getDefaultDiscountPriceAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    public function getFreightAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    public function getDescAttr($value)
    {
        return htmlspecialchars_decode($value,ENT_QUOTES);
    }

    // 预处理数据
    public function getDefaultLivePriceAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    // 预处理数据
    public function getProductsJsonAttr($value)
    {
        if($value){
            $list = [];
            $value = json_decode($value,true);
            foreach($value as $k => $v){
                $list[] = [$k,$v];
            }
            return $list;
        }
        return [];
    }

    //    预处理数据处理 轮播图
    public function getCoverAttr($value)
    {
        return explode(',',$value);
        //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
        // $arrs = explode(',',$value);
        // if($arrs && is_array($arrs) && count($arrs) > 0){
        //     $all = [];
        //     foreach($arrs as $i){
        //         $all[] = env('app.host_domin').'://'.env('app.static_host').$i;
        //     }
        //     return $all;
        // }
        // return [env('app.host_domin').'://'.env('app.static_host').$value];
    }

    //    预处理数据处理 分享图
    // public function getShareAttr($value)
    // {
    //     //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
    //     return env('app.host_domin').'://'.env('app.static_host').$value;
    // }

//    预处理数据处理
    public function getVideoAttr($value)
    {
        //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
        return env('app.host_domin').'://'.env('app.static_host').$value;
    }


    // 商城-获取商品数据  普通商品  可显示分享赚 但是 没有
    public function getList($get)
    {
        $type = isset($get['type']) ? $get['type'] : 0;
        // 是否为精选商品
        $is_hot = isset($get['is_hot']) ? $get['is_hot'] : 0;
        $oredr = 'sort desc';
        //$brand
        $where = [['status','=',1],['is_delete','=',0],['is_activity','=',0]];
        // 分类
        if($type && $type >= 1)
            $where[] = ['cid','=',$type];
        // 是否精选
        if($is_hot == 1)
            $where[] = ['is_hot','=',$is_hot];
        // 是否爆款
        if(isset($get['is_explosion']) && $get['is_explosion'] == 1)$where[] = ['is_explosion','=',$get['is_explosion']];
        // 是否福利
        if(isset($get['is_welfare']) && $get['is_welfare'] == 1)$where[] = ['is_welfare','=',$get['is_welfare']];
        // 是否新品
        if(isset($get['is_new']) && $get['is_new'] == 1)$where[] = ['is_new','=',$get['is_new']];
        // 搜索 name
        if(isset($get['name']) && $get['name'])
            $where[] = ['name','like','%'.trim($get['name']).'%'];
        // 品牌
        if(isset($get['bid']) && $get['bid'] > 0)
            $where[] = ['bid','=',$get['bid']];    
        // 排序
        if(isset($get['orderKey']) && in_array($get['orderKey'],['sales_volume','default_discount_price','add_time']))
            $oredr = 'sort desc,'.$get['orderKey']." ".(isset($get['order']) && in_array($get['order'],['desc','asc']) ? $get['order'] : 'desc');
        else if(isset($get['type']) && $get['type'] == 0)
            $oredr = 'sort desc';
        $this->queryList($get,$this->field,$where,$oredr);
        foreach($this->list['data'] as $k => $v){
            if($this->list['data'][$k]['min_money'] > 0 && $this->list['data'][$k]['default_discount_price'] > $this->list['data'][$k]['min_money'])
                $this->list['data'][$k]['default_discount_price'] = $this->list['data'][$k]['min_money'];
            if($this->list['data'][$k]['share']) $this->list['data'][$k]['share'] = getHostDominUrl($this->list['data'][$k]['share']);
        }
    }

    /**
     * 爆款、福利、新品  专区
     */
    public function shopList(){
        $where = ['status'=>1,'is_delete'=>0,'is_activity'=>0];
        $configModel = new Config();
        $shopConfig = $configModel->toData('shopConfig');
        // 爆款
        $explosionList = $this::where(array_merge($where,['is_explosion'=>1]))->order('sort desc,add_time desc')->limit((int)$shopConfig['explosion_num'])->field($this->field.',active_img')->select();
        $explosionList = $this->getMinMaxMoney($explosionList);
        // 福利
        $welfareList = $this::where(array_merge($where,['is_welfare' => 1]))->order('sort desc,add_time desc')->limit((int)$shopConfig['welfare_num'])->field($this->field.',active_img')->select();
        $welfareList = $this->getMinMaxMoney($welfareList);
        // 新品
        $newList = $this::where(array_merge($where,['is_new' => 1]))->order('sort desc,add_time desc')->limit((int)$shopConfig['new_num'])->field($this->field.',active_img')->select();
        $newList = $this->getMinMaxMoney($newList);
        return [
            'explosionList' => $explosionList,
            'welfareList' => $welfareList,
            'newList' => $newList,
            'explosion_title' => $shopConfig['explosion_title'],
            'welfare_title' => $shopConfig['welfare_title'],
            'new_title' => $shopConfig['new_title']
        ];
    }

    // 获取 价格区间
    public function getMinMaxMoney(&$list){
        if(!$list || count($list) == 0) return $list;
        foreach($list as $k => &$v){
            $arrs =  $v->toArray();
            $arrs['share_money'] = 0;
            if($list[$k]['min_money'] > 0 && $list[$k]['default_discount_price'] > $list[$k]['min_money'])$arrs['default_discount_price'] = $arrs['min_money'];
            if(isset($arrs['active_img'])  && strlen($arrs['active_img']) >= 5)$arrs['share'] = $arrs['active_img'];
            $list[$k] = $arrs;
        }
        return $list;
    }


    /**
     * @param $id 查询当前id，并进行判断数据范湖
     * @return array|null|Model|void 返回当前记录
     */
    public function getOne($request){
        $id = $request->param('id',-1);
        if(!$id || $id < 1)
            return retu_json(400,'列表记录为空');
        // ->field('id,name,title,cover,share,default_price,default_discount_price')

        $field = 'id,name,title,cover,share,desc,default_price,default_discount_price,stock,sales_volume,products_json,bid,min_money,max_money,is_activity';
        $goods = $this->where('status',1)->field($field)->find($id);
        if(!$goods)
            return retu_json(400,'没有该记录');


        // 拿取商品信息
        $list = $goods->toArray();

        // 获取到 当前需要的视频或者拼团列表的详情
        $model =  $this->getActivityVideoModel($request,$goods);

        // 拿取到商品对应的活动id 需要携带
        if($model['activityModel'])
            $list['activity_id'] = $model['activityModel']->id;

        $bool = $model['bool'];

        // 品牌信息获取
        if($goods->OneGoodsBrand){
            $list['brand'] = [
                'id' => $goods->OneGoodsBrand->id,
                'name' => $goods->OneGoodsBrand['name'],
                'cover' => $goods->OneGoodsBrand->cover ? getHostDominUrl($goods->OneGoodsBrand->cover) : '',
            ];
        }

        // 关联其商品-并且抽离 商品规格属性
        $attrArr = $goods->AttrMany->toArray();
        $newAttr = [];
        foreach($attrArr as $item){
            $newAttr[] = [
                'id' => $item['id'],
                'cost_price' =>  $item['cost_price'],
                "price"=> $item['price'],
                "discount_price"=> $item['discount_price'],
                "stock"=> $item['stock'],
                "live_price"=> $item['live_price'],
                "integral"=> $item['integral'],
                "sale"=> $item['sale'],
                "valjson" => $item['valjson'],
                "img" => getHostDominUrl($item['img'])
            ];
        }
        $attrs = GoodsAttr::getAttrDataList($attrArr);
        $linshi = [];
        foreach($attrs['data'] as $k => $v){
            $linshi[] = [
                "key"=> $k,
                'vals' => $v
            ];
        }
        $attrs = $linshi;

        // 默认没有收藏
        $list['is_collect'] = false;

        // 当前用户是否有收藏此商品
        if(isset($this->user) && $this->user){
            $list['is_collect'] = UserGoodsCollect::where(['uid'=>$this->user->id,'goods_id'=>$goods->id])->count() > 0 ? true : false;
        }

        $list['old_default_discount_price'] = $list['default_discount_price'];
        # 商品价格 区间
        if($list['min_money'] > 0 && $list['max_money']  > 0 && $list['max_money'] != $list['min_money'])
            $list['default_discount_price'] =  (string)$list['min_money'].'-'.(string)$list['max_money'];

        # 是否在直播中
        $list['lives_bool']  = false;
        $liveBroadcastGoodsModel = new LiveBroadcastGoods();
        $lives_list = $liveBroadcastGoodsModel->getReGoods($id);
        if($lives_list = $liveBroadcastGoodsModel->getReGoods($id)){
            $lives_list['is_delete'] = 0;
            if($liveBroadcastOne = LiveBroadcast::where($lives_list)->find()){
                $list['lives_bool'] = true;
                $list['lives_rootm_id'] = $liveBroadcastOne->room_id;
                // 如果是直播商品跳转过来的
                if($list['lives_bool'] && $live_get = $request->param('lives',false)){
                    if($live_get == 'lives'){
                        $list['default_discount_price'] = $newAttr[0]['live_price'];
                        // default_discount_price
                        foreach($newAttr as $k => $item){
                            $newAttr[$k]['price'] = $item['live_price'];
                        }
                    }
                }
            }
        }

        // 判断是否可以使用优惠券
        $list['coupon_true'] = (new ShopCoupon())->getCouponLimit($goods) > 0;

        // 获取到 轮播图
        if ($list['cover']) {
            foreach($list['cover'] as $k => $item) {
                $list['cover'][$k] = getHostDominUrl($list['cover'][$k]);
            }
        }

        return [
            'commodity' => $list,
            'attrs' => $newAttr,
            'attrOjb' => $attrs,
            'bool' => $bool,
            'isTrue' => $bool
        ];
    }

    /**
     * 返回到支付详情中的数据
     */
    public function getPayData($user)
    {
        $request = Request();
        $id = $request->param('id',false);
        if(!$id)
            return retu_json(400, 'id不得为空');
        $one = $this->find($id);
        if(!$one)
            return retu_json(400, '记录不存在');
        if($one->status != 1)
            return retu_json(400, '商品没有上架');
        // 以上是为基本信息都需要用到 调用基本信息判断
        $oneData = $this->isPayDataDefault($user,$request,$one);
        if(!$oneData)
            return retu_json(400,'拿取错误');
        if($oneData['code'] == 400)
            return retu_json(400,$oneData);
        $one = $oneData['list'];
        $msg = $oneData['msg'];

        // 获取到 当前需要的视频或者拼团列表的详情
        $model =  $this->getActivityVideoModel($request,$one);

        // 如果不是视频或者拼团携带进来的  进行自省购 且当前商品  开启了分销设置 可以分享和自购省
        if($model['bool'] && $one['is_sale'] == 1){
            list($one,$msg) = $this->getPurchaseProvince($user,$one,$msg);
        }

        $one['wallet_money']  = 0;

        # 商品开启-购物券-是否有购物券 -
        if($one->is_use == 1 && $one->ticket > 0 && isset($one['walletModel']) && $one['walletModel'] && $one['walletModel']['volume_balance'] > 0){
            $one['walletModel']['volume_balance'] = $one['walletModel']['volume_balance'] / 100;
            $one['wallet_money'] = $one->ticket / 100 * $one['attr']['price'];
            # 如果大于 购物券余额那么
            if($one['wallet_money'] > $one['walletModel']['volume_balance']) $one['wallet_money'] =  $one['walletModel']['volume_balance'];
            $one['wallet_money'] = number_format($one['wallet_money'],2);
            $one['wallet'] =  $one['walletModel']['volume_balance'];
            unset($one['walletModel']);
        }

        // 如果此商品有关联的id 需要返回
        if(isset($model['activityModel']) && $model['activityModel'])
            $one['activity_id'] = $model['activityModel']['id'];
        # 是否在直播中
        $one['lives_bool']  = false;
        $one['lives_rootm_id'] = 0;
        $liveBool = $request->param('lives',false);
        $liveBroadcastGoodsModel = new LiveBroadcastGoods();
        if($liveBool && $lives_list = $liveBroadcastGoodsModel->getReGoods($id)){
            $lives_list['is_delete'] = 0;
            if($liveBroadcastOne = LiveBroadcast::where($lives_list)->find()){
                $info = json_decode(json_encode($one['attr']),true);//定义一个中间变量，操作这个变量，结果赋值给$list[$key]['info']
                foreach($info as $k =>$i){
                    if($k == 'price'){
                        $info[$k] = $info['live_price'];
                        break;
                    }
                }
                $one['attr'] = $info;
                $one['lives_bool'] = true;
                $one['lives_rootm_id'] = $liveBroadcastOne->room_id;

                # 此处默认时不加 以后等后台配置
                // 隐藏自购省
                if(isset($one['purchase'])) $one['purchase'] = 0;
                // 隐藏
                if(isset($one['purchase_money'])) $one['purchase'] = 0;
            }
        }
        return [
            'data' => $one,
            'msg' => $msg
        ];
    }


    /**
     * 下单开始处理-新版
     */
    public function newInfoPay($user, $param){
        $payorder = new PayOrder();
        // 前缀数据拿取
       $verificationData = $payorder->Verification($user,$param);
       if(!$verificationData['bool']) return $verificationData;
       // 会员体系拿取-层级数据
       if(!$level = $payorder->getUserList($user->level))return retu_json(400,'请先绑定手机号码');
       $user['level'] = $level;
       return $payorder->init($user,$verificationData,$param);
    }




    /**
     * 下单开始处理
     */
    public function infoPay($user)
    {
        // 拿取参数数据进行切割
        

        // ---------------------
        $request = Request();



        fileLog("数据如下：----\r\n".date('Y-m-d H:i:s').'---前端参数：'.json_encode($request->param()).'---结束了---','goods.log');
        // 购物数量
        $num = (int)$request->param('num',0);
        if($num <= 0 || !is_numeric($num) || $num * 1 != $num)
            return retu_json(400,'购买数量不得为空，数量只能为数字');
        
        $id = $request->param('id',0);
        if($id <= 0)
            return retu_json(400,'商品id不得为空');
        $desc = $request->param('desc','');
        if(strlen(trim($desc)) >= 200)
            return retu_json(400,'备注信息过长');
        // 1 微信支付  ，  2  余额支付
        $pay_type = $request->param('pay_type',false);
        if(!$pay_type || !in_array($pay_type,[1,2]))
            return retu_json(400,'支付类型不得为空');
        // 用户的地址id不得为空
        $adders_id = $request->param('adders_id',-1);
        if($adders_id <= 0)
            return retu_json(400,'支付地址不得为空');
        // 是否使用购物券
        $wallet_bool = $request->param('wallet',false);
        $wallet_bool = $wallet_bool == 1;
        $one = $this->find($id);
        if(!$one)
            return retu_json(400,'当前商品id为空');
        // 商品信息判断开始
        if($one->status != 1)
            return retu_json(400,'商品已下架');
        // 以上是为基本信息都需要用到 调用基本信息判断
        $oneData = $this->isPayDataDefault($user,$request,$one);
        if(!$oneData)
            return retu_json(400,'拿取错误');
        if($oneData['code'] == 400)
            return retu_json(400,$oneData);
        $one = $oneData['list'];
        // 没有收货地址
        if(!isset($one['adders']) || !$one['adders'])
            return retu_json(400,'收货地址错误');
        $msg = $oneData['msg'];
        if($one['attr']['stock'] < $num)
            return retu_json(400,'抱歉，当前规格库当前只有：'.$one['attr']['stock']."，当前购买数量为：".$num);
        // 获取到 当前需要的视频或者拼团列表的详情
        $model =  $this->getActivityVideoModel($request,$one);

        /*
         * 是否为直播跳转过来的  // 且是直播 且为普通商品
        */
        $liveBool = $request->param('lives',false) && $one->is_activity == 0;
        if($liveBool){
            $liveBool = false;
            $liveBroadcastGoodsModel = new LiveBroadcastGoods();
            // 拿取正在直播中的商品
            if($lives_list = $liveBroadcastGoodsModel->getReGoods($one->id)){
                $lives_list['is_delete'] = 0;
                if($liveBroadcastOne = LiveBroadcast::where($lives_list)->field('id')->find()){
                    $liveBool = true;
                    $lives_list['live_id'] = $liveBroadcastOne->id;
                }
            }
        }

        /*  -----------------  计算金额 开始  start  --------------------- */
        // 注意此处的数据 是数据库拿取的  已经转换过金额了 此处建议所有金额操作 使用 bc函数
        $bc =  new Bc();
        // 默认单个商品支付的价格
        $price = $one['attr']['live_price'];
        if($liveBool) $price = $one['attr']['price'];
        // 计算出当前的金额 规格里的折价 乘以  数量  然后  加上   运费
        // 如果是直播 那么直播价
        $money = $bc->calcAdd($bc->calcMul($liveBool ? $one['attr']['live_price'] : $one['attr']['price'],$num,2),$one['freight'],2);

        // 判断是否为直播中跳转商品

        # 自购省 优先级 最高   需要将购物券 金额 扣掉 自购省 , 分享赚金额  直播不参与自购省
        $purchase_money = 0;$purchase_ratio = 0;$share_goods = 0;



        // 常规商品 且 该商品有自购省 直播跳转过来的 没有自购省
        if($one->is_activity == 0 && $one->is_team == 1 && !$liveBool){
            // 如果是购物券用户 且 层级为1
            if($user->level == 1 && $user->is_proceeds == 1) {
                $volumeConfig = (new Config())->getSrTypes('volumeVip');
                if($volumeConfig && isset($volumeConfig->purchase) && $volumeConfig->purchase) {
                    // 自购省百分比 *  商品价 自购省金额 数量
                    $purchase_ratio = $volumeConfig->purchase / 10;
                    $purchase_money = $bc->calcDiv($purchase_ratio * $one['attr']['price'], 100,2);
                }
                // 如果有自购省比例
            }else if($user->getLevelModel->purchase && $user->getLevelModel->purchase > 0){
                // 自购省百分比 *  商品价 自购省金额 数量
                $purchase_ratio = $user->getLevelModel->purchase;
                $purchase_money = $bc->calcDiv($user->getLevelModel->purchase * $one['attr']['price'], 100,2);
            }
            # 计算出 价钱 -   扣掉 自省购
            $money = $bc->calcSub($money,$purchase_money * $num,2);
            
        }
        /*---- 购物券开始---*/

        // 购物券余额 和 单个商品_购物券可以抵扣的金额 $one['wallet'] $one['wallet_money']
        $wallet = 0;
        $wallet_money = 0;
        $shiji_deduct_money = 0;
        // 如果有使用购物券
        if($wallet_bool && isset($one['wallet'])){
            // 用户的购物券余额
            $wallet = isset($one['wallet']) && $one['wallet'] > 0 ? $one['wallet'] / 100 : 0;
            // 用户当前商品--可以抵消的购物券金额 总购物券抵扣的金额
            $wallet_money = $bc->calcMul($num,isset($one['wallet_money']) && $one['wallet_money'] > 0 ? $one['wallet_money'] : 0,2);
            // echo "当前可以抵扣的商品-总购物券金额：$wallet_money\r\n";
            // 如果大于购物券余额
            if($wallet_money > $wallet) $wallet_money = $wallet;
            // 当前抵消的购物券 金额
            $deduct_money = $wallet_money;
            if($wallet_money >= $money){
                $deduct_money = $wallet - $money;
                $shiji_deduct_money = $money;
                // $shengyu_deduct_money = $wallet-$money;
                $money = 0.01;
            }else{
                $money = $money - $wallet_money;
                // $shengyu_deduct_money = $wallet-$wallet_money;
                $shiji_deduct_money = $wallet_money;
                $deduct_money = 0;
            }
        }
        
        /*
        dump([
            // "类型" => $type_w,
            "购买数量" => $num,
            "dssd" => '65555',
            "个人余额：" => [
                "购物券余额：" => $wallet
            ],
            "单个价格计算" => [
                "商品价格" => $one['attr']['price'],
                "购物券抵扣金额" => $price * $one->ticket / 100,// $wallet_money,
                "抵扣需要购物券" => $deduct_money,
                "自购省金额：".$one['attr']['price']." * 0.".$purchase_ratio => $purchase_money,
                "自购省比例" => $purchase_ratio
            ],
            "总的价格计算" => [
                "当前总价：" => $price * $num,
                "当前需要支付金额" => $money,
                "当前总购物券抵扣" => $wallet_money,
                "实际扣掉-购物券" => $shiji_deduct_money,
                // "当前购物券余下-余额" => $shengyu_deduct_money,
                "当前自购省金额" => $purchase_money * $num
            ]
        ]);
        exit;
          */

        $deduct_money = $shiji_deduct_money;

        /*---- 购物券结束---*/

        //dump($money,$one['freight'],$one['attr']['discount_price']);

        // 订单记录初始数据  所有的金额 都是单位分
        // 生成订单号
        $orn = getNumber();
        $orderData = [
            'uid' => $user->id, // 用户id
            'type' => 1, // 订单类型
            'order_sn' => $orn, // 订单号
            'aid' => '', // 关联商品的id,
            'addr_id'=> $one['adders']->id, // 收货地址
            'total' => $money * 100, // 支付总金额
            'freight' => $one['freight'] * 100, //  购物卷抵扣金额，单位分
            'add_time' => time(), // 下单时间
            'is_volume' => $deduct_money > 0 ? 1 : 0, // 是否使用购物券
            'volume' => $deduct_money > 0 ?  $deduct_money * 100 : 0, // 购物券金额
            'remarks' => $desc, // 订单备注
            'pay_type' => $pay_type // 支付类型
        ];
        // 订单详情数据 商品规格一定要存储
        $orderInfoData = ['json' => [ 'good_attr' => $one['attr'],'goods' => [
            'id'  => $one->id,
            'name' => $one->toArray()['name'],
            'ticket' => $one->ticket,
            'is_sale' => $one->is_sale,
            'is_use' => $one->is_use,
            'is_team' => $one->is_team,
            'status' => $one->status,
            'title' => $one->title
        ],'num'=>$num],'pay_type' => $pay_type];
        // 订单 商品数据
        $orderGoodsData = [
            'goods_id' => $one->id,
            'attr_id' => $one['attr']['id'],
            'cost' =>  $one['attr']['cost_price'] * 100, // 当前的成本价
            'price' => ($liveBool ? $one['attr']['price'] : $one['attr']['live_price']) * 100, // 如果为直播跳转那么 则是直播价 商品价
            'num' => $num,
            'freight' => $one['freight'] * 100,
            'volume' => $deduct_money * 100,
            'add_time' => time(),
            'is_sale' => $one->is_sale, // 分销 分享
            'is_team' => $one->is_team, // 累计业绩  累计消费
            'total' => $bc->calcSub($money,$one->freight) * 100// 减去当前运费
        ];

        // 如果有自购省, 且自购省 大于0 且 比例 大于 0
        if($purchase_money > 0 && $purchase_ratio > 0){
            // 订单详情里面 自购省百分比
            $orderInfoData['purchase_ratio'] = $purchase_money;
            $orderInfoData['purchase_money'] = $purchase_money * 100 * $num;
            $orderGoodsData['purchase_money']= $purchase_money * 100 * $num;
        }

        // 订单模型
        $orderModel = new Order();
        // 订单详情模型
        $orderInfoModel = new OrderInfo();
        // 订单商品模型
        $orderGoodsModel = new OrderGoods();

        $time = time();

        // 开启事务
//        $this::startTrans();

        // 当前调用的处理逻辑-- 默认就是常规商品
        $switch_type = false;

        /*---------------  金额计算开始  -----------------------------*/
        // 购物券记录  记录当前使用购物券的金额  和 购物券比例
        if($deduct_money > 0){
            $orderData['is_volume'] = 1;
            // 当前商品的设置的购物券百分比
            $orderInfoData['volume_ratio'] = $one['ticket'];
        }

        /*----  验证支付类型  -----*/
        // 如果选择是余额支付  则 余额必须大于当前 的金额
        if($pay_type == 2){
            if(!$one['walletModel'])
                $one['walletModel'] = UserWallet::where('uid',$user->id)->find();
            if(!$one['walletModel'])
                return retu_json(400,'钱包为空');
            if($one['walletModel']['balance']/100 < $money)
                return retu_json(400,'抱歉，你的余额为：'.($one['walletModel']['balance']/100).',当前订单所需金额:'.$money);
            // 微信支付 支付处理逻辑
        }else{
            if(!$user->openid)
                return retu_json(400,'用户请先授权');
        }
        /*----  验证支付类型  -----*/

        /*-----   类型判断完毕  -------*/
        // 当前商品关联的 活动模型
        $activityOneModel = false;
        $activity_log_id = $request->param('activity_log_id',0);
        $video_id = $request->param('video_id',false);
        $puid = $request->param('puid',false);
        $switch_num = 0;

        // 目前已知情况：  1常规商品，2活动-开团，3活动-开团-入团，4视频-关联商品分享，5商品-分享商品
        $title_msg = '提示信息如下'.($pay_type == 1 ? '微信支付-' : '余额支付-');

        //  常规商品开始---- 进行自省购  类型1 , 视频分享-常规商品 4，  用户分享-常规商品 5   ,   直播中，跳转购买的 类型 6
        if($one->is_activity == 0){
            // 记录分享订单表
            $UserShareOrderData = [
                'uid' => $user->id,
                'status' => 1, // 代付款
                'add_time' => $time,
                'goods_id' => $one->id,
                'total' => $orderGoodsData['total'],
                'self_money' => $purchase_money > 0 ? $purchase_money * 100 : 0
            ];
            // 视频关联-常规商品 - 分享 点击
            if($video_id && $video_id > 0){
                $videoModel = Video::find($video_id);
                // 如果没有  则 返回
                if (!$videoModel)
                    return retu_json(400, '该视频记录不存在');
                // 如果没有  则 返回
                if (!$videoModel)
                    return retu_json(400, '该视频记录不存在');
                // 视频关联 - 商品 关联的活动则 走下面的分支
                if ($videoModel['type'] == 1) {
                    // 分享者 购买者同一人
                    if($videoModel->id == $user->id){
                        $title_msg .= '--常规商品购买';
                        $switch_num = 1;
                        // 普通商品-- 处理逻辑
                        $switch_type = 'goods';
                    }else{
                        $volumeConfig = (new Config())->getSrTypes('volumeVip');
                        fileLog('参数：'.json_encode($volumeConfig),'购物券日志.log');
                        if($volumeConfig->share > 0)
                            $UserShareOrderData['p_volume_share_ratio'] = $volumeConfig->share;
                        $switch_type = 'video_share_goods';
                        $orderInfoData['json']['data_list'] = ['video_id' => $videoModel->id,'puid' => $videoModel->uid];
                        $UserShareOrderData['puid'] = $videoModel->uid;
                        $UserShareOrderData['related_id'] = $videoModel->uid;
                        $UserShareOrderData['type'] = 1;
                        $UserShareOrderData['desc'] = '视频-分享常规商品-记录';
                        $switch_num = 4;
                        $title_msg .= '视频-分享常规商品-记录';
                    }
                }
                // 用户关联-常规商品  - 分享点击
            }else if($puid && $puid > 0){
                $pUserModel = User::find($puid);
                // 如果没有  则 返回
                if (!$pUserModel)
                    return retu_json(400, '分享者用户不存在');
                // 分享者 购买者同一人
                if($pUserModel->id == $user->id){
                    $title_msg .= '--常规商品购买';
                    $switch_num = 1;
                    // 普通商品-- 处理逻辑
                    $switch_type = 'goods';
                    // return retu_json(400, '分享者和购买者不能同一人');
                }else{
                    $volumeConfig = (new Config())->getSrTypes('volumeVip');
                    fileLog('参数：'.json_encode($volumeConfig),'购物券日志.log');
                    if($volumeConfig->share > 0)
                        $UserShareOrderData['p_volume_share_ratio'] = $volumeConfig->share;
                    $switch_num = 5;
                    $UserShareOrderData['type'] = 2;
                    $orderInfoData['json']['data_list'] = ['puid' => $pUserModel->id];
                    $UserShareOrderData['puid'] = $pUserModel->id;
                    $UserShareOrderData['desc'] = '商品常规商品-分享常规商品-记录';
                    $title_msg .= '商品常规商品-分享常规商品-记录';
                    $switch_type = 'user_share_goods';
                }
                // 如果为直播 且是从直播列表中跳转过来的
            }else if($liveBool){
                $switch_type = 'lives_goods_add';
                // 存储直播信息 需要拿取到 主播用户id, 当前直播的列表id,直播商品id
                $liveBroadcastGoodsOne =  LiveBroadcastGoods::where(['goods_id' => $one->id,'is_delete' => 0])->field('id,commission')->find();
                // 存储直播中分享的佣金比例
                $commission = $liveBroadcastGoodsOne ?  $bc->calcMul($liveBroadcastGoodsOne->commission * $num , $one['attr']['live_price'])  : 0;
                $orderInfoData['json']['lives'] = [
                    'uid' => $lives_list['uid'],
                    'live_id' => $lives_list['live_id'],
                    'live_goods_id' => $liveBroadcastGoodsOne ? $liveBroadcastGoodsOne->id : 0,
                    'live_price'    => $one['attr']['live_price'],
                    'commission'    => $commission, // 佣金
                    'commission_rato'    => $liveBroadcastGoodsOne ? $liveBroadcastGoodsOne->commission : 0 // 佣金比例
                ];
                $userShareMiao = $bc->calcMul($commission, 100);
                $UserShareOrderData['type'] = 3;
                $UserShareOrderData['puid'] = $lives_list['uid'];
                $UserShareOrderData['miao'] =$userShareMiao;
                // fileLog('直播价钱位：'.$userShareMiao,'直播分享商品.log');
                $UserShareOrderData['related_id'] = $lives_list['live_id'];
                $UserShareOrderData['live_price'] = $one['attr']['live_price'] * 100;
                $UserShareOrderData['live_miao_ratio'] = $liveBroadcastGoodsOne ? $liveBroadcastGoodsOne->commission : 0;
                $UserShareOrderData['desc'] = '直播商品-直播跳转商品-分享';
                $title_msg .= '直播带货-直播中-用户点击购买';
                $switch_num = 6;
                // 普通 - 常规商品 立即购买
            } else {
                $title_msg .= '--常规商品购买';
                $switch_num = 1;
                // 普通商品-- 处理逻辑
                $switch_type = 'goods';
            }
            if($switch_num > 0)
                $orderData['type'] = 1;
            // 拼团-活动列表-必须得有团id   自己开团 ， 没有拉人   或者.   自己开团 有上级的团
        }else if(isset($model['activityModel'])){
            $activityOneModel = $model['activityModel'];
            if($activityOneModel->end_time < time())return retu_json(400,'抱歉，当前活动已结束');
            // 开团记录的基本数据  -  当前
            $activity_logData = [
                //  'oid' => $orderId, // 订单id
                'aid' => $activityOneModel->id, // 活动id
                'uid' => $user->id, // 用户id
                'price' => $one['attr']['price'] * 100, // 当前商品的规格价
                'discount_price' => $one['attr']['discount_price'] * 100, // 当前商品的折扣价
                'miao' => 0, // 喵呗  单位分
                'num' => $activityOneModel->num,
                'type' => $activityOneModel->type, // 计算方式  固定值 和 百分比
                'content' => $activityOneModel->content ? json_encode($activityOneModel->content) : $activityOneModel->content, // 开团计算值
                'end_time' => $time + $activityOneModel->hours * 3600, // 拼团结束时间 内
                'add_time' => $time, // 添加时间
                'goods_id' => $one->id // 拼团id
            ];
            // 判断当前商品是否有关联的 活动 并且 不是入团 没有个人开团活动列表 类型  2
            if(!$activity_log_id && isset($model['activityModel'])){
                $one['activityModel'] = $model['activityModel'];
                if($one['activityModel']['status'] != 1)
                    return retu_json(400,'当前活动已下线');
                $switch_type = 'activity_goods_create';
                $switch_num = 2;
                $orderData['type'] = 2;
                $title_msg .= '商品-开团处理';
                // 有开团信息 , 且 入团 类型 3
            }else if($activity_log_id && $activity_log_id > 0){
                if(isset($puid)) $puid = $puid;
                fileLog('开团id:'.$activity_log_id,'goods.log');
                # 拿取 老团
                $ActivityLogIdModel = ActivityLog::where(['uid'=>$puid,'aid'=>$activity_log_id,'astatus'=>0])->order('add_time asc')->find();
                $orderData['type'] = 2;
                #$ActivityLogIdModel = ActivityLog::find($activity_log_id);
                # 没有该  拼团信息 -- 开团处理
                if(!$ActivityLogIdModel){
                    if(!Activity::find($activity_log_id)) return retu_json(400,'没有该活动');
                    $switch_num = 2;
                    $title_msg .= '商品-开团处理';
                    $switch_type = 'activity_goods_create';
                }else{
                    // 如果 是本人  ---
                    if($ActivityLogIdModel->uid == $user->id){
                        $switch_num = 2;
                        $title_msg .= '商品-开团处理';
                        $switch_type = 'activity_goods_create';
                    }else{
                        if($ActivityLogIdModel->astatus != 0)
                            return retu_json(400,'当前拼团已完成');
                        if($ActivityLogIdModel->end_time <= time())
                            return retu_json(400,'开团时间已结束');
                        if(!$activityModel = Activity::find($ActivityLogIdModel->aid))
                            return retu_json(400,'拼团活动对应的活动列表不存在');
                        if(!in_array($one->id,$activityModel->goods))
                            return retu_json(400,'该商品没有在拼团活动中');
                        if(!in_array($one->id,$activityModel->goods))
                            return retu_json(400,'该商品没有在拼团活动中');
                        if($ActivityLogIdModel->num == $ActivityLogIdModel->nums)
                            return retu_json(400,'该拼团人数已满，返回首页重新下单');
                        #return retu_json(400,'自己不得加入自己的拼团');
                        // 当前开团列表关联的活动 id 是否 对应 当前的商品管理的活动id
                        // 存储 老团的信息 并存储上个团的信息
                        $orderInfoData['json']['activityLogId'] = $ActivityLogIdModel->id;
                        $activity_logData['pid'] = $ActivityLogIdModel->id;
                        $switch_type = 'activity_goods_add';
                        $title_msg .= '商品-开团处理-入团处理';
                        $switch_num = 3;
                    }
                }
                #    return retu_json(400,'没有当前开团信息');
            }
        }else{
            return retu_json(400,'五不像，参数错误');
        }
        /*----------------  类型判断完毕  ----------------------------*/

        if(!$switch_type)
            return retu_json(400,'参数不对');

        $orderInfoData['switch_num'] = $switch_num;

        // 添加redis
        $sr = new SelfRedis();
        $sr->redis->select(5);

        if($sr->redis->getNx('order_create_'.$user->id))
            return retu_json(400,'等待5秒后尝试');
        $this::startTrans();
        // 异常处理
        try{
            // 限流  - 单个用户 10秒只能生成一笔订单 防止 产生多个订单号
            $sr->redis->setNx('order_create_'.$user->id,$orn,10);
            //------- 订单表开始 ------
            // 生成订单表
            $orderId = $orderModel->insertGetId($orderData);
            if(!$orderId)
                return retu_json(400,'订单生成失败');
            // 订单详情表
            $orderInfoData['oid'] = $orderId;
            $orderInfoData['json'] = json_encode($orderInfoData['json']);

            // 插入到订单详情表
            $orderInfoId = $orderInfoModel->insertGetId($orderInfoData);
            if(!$orderInfoId)
                return retu_json(400,'订单生成失败11');
            // 插入到订单-商品表
            $orderGoodsData['order_id'] = $orderId;
            $orderGoodsId = $orderGoodsModel->insertGetId($orderGoodsData);
            if(!$orderGoodsId)
                return retu_json(400,'订单生成失败22');
            // 处理结果的数据
            $return_data = ['msg'=>'ok'];

            // 处理逻辑
            switch($switch_type){
                // 常规商品操作  - 不用做额外的处理  直接
                case 'goods':
                    break;
                // 视频分享商品操作
                case 'video_share_goods':
                    $UserShareOrderData['oid'] = $orderId;
                    $UserShareOrderId = UserShareOrder::insertGetId($UserShareOrderData);
                    if(!$UserShareOrderId)
                        return retu_json(400,'视频分享记录失败，重新尝试');
                    break;
                // 用户分享商品操作
                case 'user_share_goods':
                    $UserShareOrderData['oid'] = $orderId;
                    $UserShareOrderId = UserShareOrder::insertGetId($UserShareOrderData);
                    if(!$UserShareOrderId)
                        return retu_json(400,'用户分享商品记录失败，重新尝试');
                    break;
                // 拼团-开团 个人 -  无需 上级团主
                case 'activity_goods_create':
                    // 拼团列表模型-插入一条新的记录
                    $ActivityLogModel = new ActivityLog();
                    // //  'oid' => $orderId, // 订单id
                    if(isset($activity_logData))
                        $activity_logData['oid'] = $orderId;
                    $ActivityLogId = $ActivityLogModel->insertGetId($activity_logData);
                    if(!$ActivityLogId)
                        return retu_json(400,'生成历史订单错误，请重新查看');
                    $return_data['data']['log_id'] = $ActivityLogId;
                    break;
                // 拼团-加入团
                case 'activity_goods_add':
                    // 拼团列表模型-插入一条新的记录
                    $ActivityLogModel = new ActivityLog();
                    if(!$ActivityLogIdModel)
                        return retu_json(400,'没有上级活动团的记录');
                    if(isset($activity_logData)){
                        $activity_logData['oid'] = $orderId;
                        $activity_logData['pid'] = $ActivityLogIdModel->id;
                    }
                    $ActivityLogId = $ActivityLogModel->insertGetId($activity_logData);
                    if(!$ActivityLogId)
                        return retu_json(400,'生成历史订单错误，请重新查看');
                    $return_data['data']['log_id'] = $ActivityLogId;
                    break;
                // 直播分享-直播佣金
                case 'lives_goods_add':
                    $UserShareOrderData['oid'] = $orderId;
                    $UserShareOrderId = UserShareOrder::insertGetId($UserShareOrderData);
                    if(!$UserShareOrderId) return retu_json(400,'用户直播商品记录失败，重新尝试');
                    break;
                // 其他情况 不处理
                default:
                    break;
            }

            $return_data['data']['pay_type'] = $pay_type;


            // 微信支付
            if($pay_type == 1){
                if($money - 0 == 0){
                    $money = 0.01;
                }
                // 调用微信支付返回信息
                // $user->is_fictitious == 1 虚拟用户
                $a = new WeixinPay($user->openid,$orn.'0','订单支付',$money); // $money $user->is_fictitious == 1 ? 0.01 : $money
                $pay = $a->pay(); //下单获取返回值
                if(!$pay || !$pay['code'])
                    return retu_json(400,isset($pay['msg']) ? $pay['msg'] : '`麻烦重新尝试');
                if(isset($pay['data']['appId']))
                    unset($pay['data']['appId']);
                $pay['data']['orderid'] = $orn;
                $return_data['data'] = $pay['data'];
                $return_data['data']['title_msg'] = $title_msg;
                $return_data['data']['pay_type'] = $pay_type;
                $pay_log = PayLog::insertGetId(['uid'=>$user->id,'oid'=>$orderId,'orn'=>$orn.'0','request'=>json_encode($return_data),'explain'=>$title_msg,'ip'=>0]);//写入支付记录
                # 微信支付需要推送到队列中
                $configList = Config::where('type','business')->find();
                if($configList && $configObj = json_decode($configList['content'],true))
                    MyJob::pushQueue('OrderPayDelay',['id'=>$orderId],$configObj['overtime'] * 60);
                // 余额支付 - 先扣掉会员的钱  之后  进行 前端回调 处理  或者 redis 队列 执行 -  此处采用 前端回调处理逻辑
            }else{
                //Log::write('余额支付开启',$user->id.'---余额---'.$orderId);
                // 写入缓存
                $sr->redis->set('order_pay_'.$orn,1);
                $isRedis = true;
                $return_data['msg'] = '余额支付ok';
                $return_data['data']['orderid'] = $orn;
                $return_data['data']['title_msg'] = $title_msg;
                $return_data['data']['pay_type'] = $pay_type;
                $pay_log = PayLog::insertGetId(['uid'=>$user->id,'oid'=>$orderId,'orn'=>$orn.'0','request'=>json_encode($return_data),'explain'=>$title_msg,'ip'=>0]);//写入支付记录
                if(!$pay_log)
                    return retu_json(400,'支付记录失败');
                // 拿取模型数据
                $orderOrnModel = $orderModel->where('order_sn',$orn)->find();
                $orderInfoIdModel = $orderInfoModel->where('oid',$orderOrnModel->id)->find();
                $list = $orderModel->completeOrder([
                    'orderOrnModel' => $orderOrnModel,
                    'orderInfoModel' => $orderInfoIdModel,
                    'userModel' => $user
                ]);
                if(!$list || !$list['bool'])
                    return retu_json(400,'错误');
                $one['walletModel']['balance'] = $one['walletModel']['balance'] - $money * 100;
                $okMoney = $one['walletModel']->save();
                if(!$okMoney)
                    return retu_json(400,'余额支付错误，麻烦重新尝试');
                # 所有操作  钱包 都需要走钱包表
                $WalletOperationLogData = ['uid'=>$user->id,'reward'=> $money*100,'status'=>2,'type'=>1,'extend'=>'order','extend_id'=>$orderOrnModel->id,'describe'=>'订单支付-余额支付','add_time'=>$time];
                if(!WalletOperationLog::insertGetId($WalletOperationLogData))
                    return retu_json(400,'余额支付，扣除余额-记录失败');
                # 操作余额 需要记录  余额 支付 金额
                $balanceLogId = Db::name('balance_log')->insertGetId(['type' => 2,'uid' =>$user->id,'add_time' => time(),'relation_id' =>  $orderId,'num' => $money * 100]);
                if(!$balanceLogId) return retu_json(400,'余额支付，扣除-余额-记录失败，重试');
//                Log::write('余额支付跑完了',$user->id.'---余额---'.$orderId);
            }
            if(!$pay_log)
                return retu_json(400,'支付记录更新失败，请重新尝试');
            # 判断当前商品库存的方式  // 拍下减库存 $one
            if($one->is_stock == 1){
                // 商品规格减库存
                if(isset($one['attr']['id']) && $goodsAttrModel = GoodsAttr::find($one['attr']['id']))
                    GoodsAttr::where('id',$one['attr']['id'])->update(['stock' =>  $goodsAttrModel->stock - $num > 0 ? $goodsAttrModel->stock : 0]);
                // 当前商品减库存
                Goods::where('id',$one->id)->update(['stock' => $one->stock - $num > 0 ? $one->stock - $num : 0]);
            }
            # 如果有拼团记录id
            if(isset($ActivityLogId) && $ActivityLogId > 0) $return_data['data']['log_id'] = $ActivityLogId;
            // 提交事务
            $this::commit();
            return $return_data;
        }catch (Exception $e){
            $this::rollback();
            // 是否需要删除缓存
            if(isset($isRedis) && $isRedis)
                $sr->redis->del('order_pay_'.$orn);
            return $e->getMessage();
        }
    }

    /**
     * 获取到自购省的
     * @param $user  用户模型 当前用户
     * @param $one  商品模型id
     */
    public function getPurchaseProvince($user,$one,$msg){
        /*
        // 有等级用户 且 是常规商品 不是拼团  也没有从视频那边跳转过来 才有自购省 且 当前商品 是 分销设置开启
        if($user->level >= 0 && $user->getLevelModel && $user->getLevelModel->purchase > 0 && $one['is_sale'] == 1){
            $one['purchase'] = $user->getLevelModel->purchase;
            $bc = new Bc();
            $one['purchase_money']  = $bc->calcDiv($bc->calcMul($one['attr']['price'],$user->getLevelModel->purchase,2),100,2);
            $msg .= '-等级-自购省';
        }
         */

        $bc = new Bc();
        // 如果等级等于 1 且 当前有自购省
        if($one['is_sale'] == 1 && $user->level == 1 && $user->is_proceeds == 1 ){
            $volumeConfig = (new Config())->getSrTypes('volumeVip');
            $one['purchase'] = $volumeConfig->purchase/10;
            // 该用户的 比例
            $one['purchase_money']  = $bc->calcDiv($bc->calcMul($one['attr']['price'],$volumeConfig->purchase/10,2),100,2);
            $msg .= '-购物券-自购省';
            // 有等级用户 且  常规商品  不是拼团       有等级用户 且 是常规商品 不是拼团  也没有从视频那边跳转过来 才有自购省 且 当前商品 是 分销设置开启
        }else if($user->level >= 0 && $user->getLevelModel && $user->getLevelModel->purchase > 0 && $one['is_sale'] == 1){
            $one['purchase'] = $user->getLevelModel->purchase;
            $one['purchase_money']  = $bc->calcDiv($bc->calcMul($one['attr']['price'],$user->getLevelModel->purchase,2),100,2);
            $msg .= '-等级-自购省';
        }
        return [$one,$msg];
    }

    /**
     * 根据当前的商品模型获取到是否有对应的拼团活动 或者视频活动 因为拼团活动和视频详情跳转的 不能使用自购省
     * @param $request tp请求对象获取参数
     * @param $one 商品id当前的模型
     * @return array|void 返回的数据
     */
    public function getActivityVideoModel($request,$one)
    {
        $videoId = $request->param('video_id',0);
        $list = [
            'bool' => true,
            'activityModel' => false,
            'videoModel' => false
        ];
        // 如果是常规商品
        if($one['is_activity'] == 0){
            return $list;
        }
        // 判断是否需要不显示自购省
        $activityId = $request->param('activity_id',0);
        // 拼团活动列表 前端传递 可以省去关联
        if($activityId && $activityId > 0 ){
            $activityData = (new Activity())->getActivitys($activityId,$one->id);
            // 如果400 直接返回
            if($activityData['code'] == 400)
                return retu_json($activityData);
            $list['activityModel'] = $activityData['model'];
            $list['bool'] = false;
            // 如果没有  则 拿取 商品中的拼团id 关联
        }else if($one->is_activity > 0){
            $activityModel =  (new Activity())->getActivitysGoods($one->id);
            if($activityModel && $activityModel->status == 1)
                $list['activityModel'] = $activityModel;
        }

        // 如果不是常规商品
        if($one['is_activity'] == 1){
            $list['bool'] = false;
            return $list;
        }

        // 如果没有开启 分销设置 分享和自购省
//        if($one['is_sale'] == 1){
//            $list['bool'] = false;
//            return $list;
//        }

        // 判断是否为视频列表点击的 视频可能关联的是商品 或者活动
        /*---    先空着   ---*/
        if($videoId && $videoId > 0){
            $videoData = (new Video())->getVideo($videoId);
            // 如果400 直接返回
            if($videoData['code'] == 400)
                return retu_json($videoData);
            $list['videoModel'] = $videoData['model'];
            $list['bool'] = false;
        }
        return $list;
    }


    /**
     * @param $user
     * @param $request
     * @return array|null|Model|void 返回当前支付详情的信息
     */
    public function isPayDataDefault($user,$request,$one)
    {
        $msg = '';
        $id = $request->param('id',false);
        if(!$id)
            return retu_json(400,'id不得为空');
        $num = $request->param('num',false);
        if(!$num)
            return retu_json(400,'数量不得为空');
        $attr_id = $request->param('attr_id',0);
        if(!$attr_id || $attr_id <= 0)
            return retu_json(400,'规格参数id不得为空');
//        $one = $this->field('id,name,title,add_time,cover,share,ticket,freight,is_activity')->find($id);
//        if(!$one)
//            return retu_json(400,'该记录不存在');
        // 关联其商品-并且抽离 商品规格属性
        if(!$one->AttrMany)
            return retu_json(400,'商品规格信息错误');
        // 拿取到商品规格组信息
        $attrArrs = $one->AttrMany->toArray();
        // 找到符合的商品规格信息id
        foreach($attrArrs as $item){
            // 规格参数数组id 且 商品id等于 关联的id
            if($item['id'] == $attr_id && $item['product_id'] = $one['id']){
                $item['img'] = getHostDominUrl($item['img']);
                $one['attr'] = unsetDataKeys($item,'color,size,upd_time');
                break;
            }
        }
        // 如果没有规则 就返回
        if(!$one['attr'])
            return retu_json(400,'商品规格信息不存在---'.$attrArrs[0]['id']);
        unset($one['AttrMany']);
        $msg = '支付详情-';
        // 地址列表 并且拿取最大的一条, 商品支付和查看详情 如果有参数则拿取参数上面的地址
        if( $user->getAddersMany){
            // 调用支付情况
            $adders_id = $request->param('adders_id',-1);
            if($adders_id && $adders_id >= 1){
                $one['adders'] = UserAddress::find($adders_id);
                if(!$one['adders'])
                    return retu_json(400,'收货地址不得为空');
                if($one['adders']['uid'] !== $user->id)
                    return retu_json(400,'收货地址和用户不一致');
            }
            // 如果没有拿取第一条数据
            if(!isset($one['adders']) || !$one['adders'])
                $one['adders'] = $user->getAddersMany()->where(['is_default'=>1,'uid'=>$user->id,'is_delete'=>0])->find();
            // 拿取到名称 进行赋值
            if($one['adders']){
                $DistrictModel = new District();
                $listArrs = $one['adders']->toArray();
                $whereIn = [$listArrs['province'],$listArrs['city'],$listArrs['area']];
                $province =  $DistrictModel->whereIn('id',$whereIn)->select()->toArray();
                if($province && count($province) == 3){
                    $one['adders']['province'] = $province[0]['name'];
                    $one['adders']['city'] = $province[1]['name'];
                    $one['adders']['area'] = $province[2]['name'];
                    $msg .= '有地址-';
                }else{
                    unset($one['adders']);
                }
            }
        }
        // 获取到购物券
        if($one->is_use == 1 && $one->ticket > 0){
            $walletModel = UserWallet::where('uid',$user->id)->find();
            if($walletModel && $walletModel->volume_balance > 0){
                $one['walletModel'] = $walletModel;
                // 用户的购物券余额
                $one['wallet'] = $walletModel->volume_balance;
                // 用户当前可以抵消的购物券
                $one['wallet_money'] = $one['attr']['price'] * $one->ticket / 100;
                // 如果小于  则  等于
                if($one['wallet'] < $one['wallet_money']){
                    $one['wallet_money'] = $one['wallet'];
                }
                $msg .= '购物券-';
            }
        }

        return [
            'code' => 200,
            'list' => $one,
            'msg' => $msg
        ];
    }

    /**
     * 获取分享页面信息
     * @param $id  商品id
     * @return array default_discount_price,title,share
     */
    public function getShareInfo($id){
        try{
            if(empty($id)) exception('找不到该商品!');
            $ret = $this->where(['id'=>$id,'is_delete'=>0])->whereIn('status','1,3,4')->field('default_discount_price,title,share')->find();
            return $ret?$ret->toArray():[];
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * 获取状态非下架或禁售的商品
     * @param $id  商品id
     * @return array default_discount_price,title,share
     */
    public function getGoodsStatus($id){
        try{
            if(empty($id)) exception('找不到该商品!');
            $ret = $this->where(['id'=>$id,'is_delete'=>0])->whereIn('status','1,3,4')->field('id')->find();
            return $ret?:[];
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * 获取视频分享商品列表
     * @param $id  商品id
     * @return array default_discount_price,title,share
     */
    public function getGoods($user){
        try{
            if(empty($user)) exception('登录信息已过期，请重新登录!');
            $data = Input('post.');
            $where = [
                ['status','=', 1],
                ['is_sale','=', 1],
                ['is_activity','=', 0],
                ['is_delete','=', 0],
            ];
            if(!empty($data['title'])){
                $where[] = ['title', 'like', '%'.trim($data['title']).'%'];
            }
            #设置已选择商品
            if(!empty($data['gid'])) $gid = $data['gid'];
            else $gid = 0;
            #排序设置
            $orderby = 'is_hot desc';
            if(!empty($data['hot'])&&$data['hot'] == 1) $orderby = 'is_hot desc';
            elseif(!empty($data['sales'])&&$data['sales'] == 2) $orderby = 'sales_volume asc';
            elseif(!empty($data['sales'])&&$data['sales'] == 1) $orderby = 'sales_volume desc';
            elseif(!empty($data['commission'])&&$data['commission'] == 2) $orderby = 'default_price asc';
            elseif(!empty($data['commission'])&&$data['commission'] == 1) $orderby = 'default_price desc';
            elseif(!empty($data['price'])&&$data['price'] == 2) $orderby = 'default_price asc';
            elseif(!empty($data['price'])&&$data['price'] == 1) $orderby = 'default_price desc';
            $level = (new UserLevel())->where(['id'=>$user['level']])->find();
            if($level['share'] < 1) exception('暂无添加商品的权限，请提升会员等级!');
            #分页设置
            $limit = isset($data['limit'])&&!empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $field = 'id,title,share,default_price,default_discount_price,is_hot,sales_volume';
            $item = $this->where($where)->field($field)->order($orderby)->paginate($limit, false, array('query'=>$query));
            $goods = empty($item) ? array():$item->toArray();
            if(!empty($goods['data'])){
                foreach($goods['data'] as $k=>$v){
                    $goods['data'][$k]['share_commission'] = number_format(($v['default_price']*($level['share']/100)),2,'.','');
                    if($gid){
                        if($v['id'] == $gid) $goods['data'][$k]['select'] = 1;
                        else  $goods['data'][$k]['select'] = 2;
                    } else  $goods['data'][$k]['select'] = 0;
                }
            }
            return $goods;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    // 一对多关联 获取到商品规格信息
    public function AttrMany()
    {
        // 商品规格表模型类，商品规格表的字段,当前表的id
        return $this->hasMany(GoodsAttr::class,'product_id','id');
    }

    // 一对多关联 获取到商品评论信息
    public function GoodsCommentMany()
    {
        // 商品评论模型类，商品评论表的字段goods_id,当前表的id
        return $this->hasMany(GoodsComment::class,'goods_id','id');
    }

    // 一对一关联  关联品牌表
    public function OneGoodsBrand()
    {
        return $this->hasOne(GoodsBrand::class,'id','bid');
    }

    // 一对多关联  店铺优惠券
    public function ShopCouponMany()
    {
        return $this->hasMany(ShopCoupon::class,'shop_id','shop_id');
    }

    // 一对一关联  关联品牌表
    /*
    public function OneUserWallet()
    {
        //return $this->hasOne(UserWallet::class,'id','uid');
    }
    */
}